package ucap.com.lesanapp.base.impl;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Vibrator;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.annotation.Table;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGABanner;
import retrofit2.http.GET;
import ucap.com.lesanapp.R;
import ucap.com.lesanapp.activitys.NewsDetailedActivity;
import ucap.com.lesanapp.base.BasePager;
import ucap.com.lesanapp.bean.DateBean;
import ucap.com.lesanapp.bean.TopNewHeadBean;
import ucap.com.lesanapp.global.Constants;
import ucap.com.lesanapp.global.SettingsModelState;
import ucap.com.lesanapp.utils.GetDateForServiceUtils;
import ucap.com.lesanapp.utils.NetworkStateUtils;
import ucap.com.lesanapp.utils.PrefUtils;
import ucap.com.lesanapp.view.WebViewDialog;


/**
 * Created by Administrator on 2016/7/27.
 * 区县
 */
public class TopNewsBase extends BasePager {

    @Bind(R.id.lv_top_news_content)
    ListView lvContent;
    @Bind(R.id.sr_top_news_refresh)
    SwipeRefreshLayout srRefresh;
    @Bind(R.id.tv_click_laoding)
    TextView tvClickLoading;
    ArrayList<DateBean.RowsBean> mListDate;
    ArrayList<TopNewHeadBean.RowsBean> mTopNewsHeadList;

    /*
    内容分类
     */
    ArrayList<DateBean.RowsBean> mListFocusNews;//要闻
    ArrayList<DateBean.RowsBean> mListVideo;//视频
    ArrayList<DateBean.RowsBean> mListPolicy;//政策解读
    private MyAdapter myAdapter;
    private HttpUtils httpUtils;
    private GetDateForServiceUtils dateUtils;
    private int model;
    private int networkType;
    private BGABanner banner;
    private TextView tvTopNewsTitle;
    private BitmapUtils bitmapUtils;
    private View head;
    //handler延时发消息，试头条新闻出现轮播功能

    public TopNewsBase(Activity mActivity) {
        super(mActivity);
    }

    @Override
    public void intiDate() {
        View view = View.inflate(mActivity, R.layout.base_top_news, null);
        ButterKnife.bind(this, view);
        flContent.addView(view);
        mListDate = new ArrayList<>();
        mListFocusNews = new ArrayList<>();
        mListPolicy = new ArrayList<>();
        mListVideo = new ArrayList<>();
        myAdapter = new MyAdapter();
        getType();
        addListViewHeadView();
        addFooterView();
        srRefresh.setVisibility(View.INVISIBLE);
        tvClickLoading.setVisibility(View.GONE);
        tvClickLoading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getType();//从新获取网络环境和浏览模式
                tvClickLoading.setVisibility(View.GONE);
                dateUtils.getDateFocusNews(httpUtils);
                getImagesForService();//从新获取头条新闻的轮播数据
            }
        });
    }


    @Override
    public void intiDateForService() {

        dateUtils = new GetDateForServiceUtils(mActivity, myAdapter, mListFocusNews, mListVideo, mListPolicy, srRefresh, lvContent, tvClickLoading
        );
        httpUtils = new HttpUtils();
        lvContent.setEnabled(false);
        int height = mActivity.getWindowManager().getDefaultDisplay().getHeight();
        TranslateAnimation animation = new TranslateAnimation(0, 0, -height, 0);
        animation.setDuration(300);
        lvContent.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                myAdapter.notifyDataSetChanged();
                srRefresh.setVisibility(View.VISIBLE);
                lvContent.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        dateUtils.getDateFocusNews(httpUtils);//由本地缓存的情况下,也会请求网络数据更新本地缓存

        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /**
                 将头部itemID减去,排除用户点击底部发生角标越界
                 */
                int index = position - 1;
                if (index >= 0 && index < myAdapter.getCount()) {
                    DateBean.RowsBean item = myAdapter.getItem(index);
                    if (item != null) {
                        Intent intent = new Intent(mActivity, NewsDetailedActivity.class);
                        intent.putExtra("title", item.getCHANNELNAME());
                        intent.putExtra("code", item.getID());
                        intent.putExtra("head", item.getTITLE());
                        if (position >= 2 && position <= 4) {
                            intent.putExtra("cid", Constants.ID_FOCUS_NEW);
                        } else if (position >= 6 && position <= 8) {
                            intent.putExtra("cid", Constants.ID_VIDEO);
                        } else if (position >= 10 && position <= 12) {
                            intent.putExtra("cid", Constants.ID_POLICY);
                        }
                        mActivity.startActivity(intent);
                    } else {
                        return;
                    }
                }
            }
        });
        lvContent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                int index = position - 1;
                if (index >= 0 && index < myAdapter.getCount()) {
                    DateBean.RowsBean item = myAdapter.getItem(index);
                    if (item != null) {
                        Vibrator vibrator = (Vibrator) mActivity.getSystemService(mActivity.VIBRATOR_SERVICE);
                        vibrator.vibrate(60);
                        String newId = "";
                        if (position >= 2 && position <= 4) {
                            newId = Constants.ID_FOCUS_NEW;
                        } else if (position >= 6 && position <= 8) {
                            newId = Constants.ID_VIDEO;
                        } else if (position >= 10 && position <= 12) {
                            newId = Constants.ID_POLICY;
                        }
                        WebViewDialog.showDialog(mActivity, item.getID(), item.getTITLE(), newId);
                    }
                }
                return true;
            }
        });
        /**
         * 刷新数据
         */
        srRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getType();//从新获取网络环境和浏览模式
                getImagesForService();//从新获取头条新闻的轮播数据
//                headModel();//头条是否显示
                addFooterView();// 刷新 公示公告&&舆情回应
                dateUtils.getDateFocusNews(httpUtils);//重新获取要闻数据

            }
        });


    }

    /**
     * 添加 公示公告&&舆情回应
     */
    public void addFooterView() {
        final HttpUtils utils = new HttpUtils();
        final BitmapUtils utils1 = new BitmapUtils(mActivity);
        Log.i("responseInfo", Constants.URL_Notice_NEWS);
        utils.send(HttpMethod.GET, Constants.URL_Notice_NEWS, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {//先添加公示公告
                Log.i("responseInfo", responseInfo.result);
                Gson gson = new Gson();
                DateBean dateBean = gson.fromJson(responseInfo.result, DateBean.class);
                final View view = View.inflate(mActivity, R.layout.item_top_news_footer, null);
                final LinearLayout llNotice = (LinearLayout) view.findViewById(R.id.ll_notice);
                final LinearLayout llOpinion = (LinearLayout) view.findViewById(R.id.ll_opinion);
                List<DateBean.RowsBean> rows = dateBean.getRows();
                llNotice.removeAllViews();//先删除添加的item，在刷新数据时才不会出现重复数据
                llOpinion.removeAllViews();
                for (final DateBean.RowsBean rowsBean : rows) {
                    addItem(rowsBean, llNotice, Constants.ID_FOCUS_Notice);
                }
                utils.send(HttpMethod.GET, Constants.URL_OPINION_NEWS, new RequestCallBack<String>() {//在获取 舆情回应
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Gson gson = new Gson();
                        DateBean dateBean = gson.fromJson(responseInfo.result, DateBean.class);
                        List<DateBean.RowsBean> rows = dateBean.getRows();
                        for (final DateBean.RowsBean rowsBean : rows) {
                            addItem(rowsBean, llOpinion, Constants.ID_FOCUS_opinion);
                        }
                        if (lvContent.getFooterViewsCount() == 0)//只添加一次
                            lvContent.addFooterView(view);//最后在添加给listView
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {

                    }
                });

            }

            /**
             * 添加item
             * @param rowsBean
             * @param llRoot
             */
            public void addItem(final DateBean.RowsBean rowsBean, LinearLayout llRoot, final String cid) {
                final View item = View.inflate(mActivity, R.layout.item_date_content, null);
                ImageView ivPhoto = (ImageView) item.findViewById(R.id.iv_news_photo);
                if (rowsBean.getPATHANDURL().isEmpty()) {
                    ivPhoto.setVisibility(View.GONE);
                } else {
                    //图文模式
                    if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
                        ivPhoto.setVisibility(View.VISIBLE);
                        utils1.display(ivPhoto, rowsBean.getPATHANDURL());
                    } else if (model == SettingsModelState.MODEL_TEXT) {
                        //文本模式
                        ivPhoto.setVisibility(View.GONE);
                    } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
                        //智能模式
                        if (networkType == ConnectivityManager.TYPE_WIFI) {
                            //wifi状态
                            ivPhoto.setVisibility(View.VISIBLE);
                            utils1.display(ivPhoto, rowsBean.getPATHANDURL());
                        } else {
                            ivPhoto.setVisibility(View.GONE);
                        }
                    }
                }
                TextView tvTitle = (TextView) item.findViewById(R.id.tv_news_title);
                TextView tvTime = (TextView) item.findViewById(R.id.tv_news_time);
                TextView tvType = (TextView) item.findViewById(R.id.tv_news_type);
                tvTitle.setText(rowsBean.getTITLE());
                tvTime.setText(rowsBean.getTIME());
                tvType.setText(rowsBean.getCHANNELNAME());
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(mActivity, NewsDetailedActivity.class);
                        intent.putExtra("title", rowsBean.getCHANNELNAME());
                        intent.putExtra("code", rowsBean.getID());
                        intent.putExtra("head", rowsBean.getTITLE());
                        intent.putExtra("cid", cid);
                        mActivity.startActivity(intent);
                    }
                });
                llRoot.addView(item);
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }

    /**
     * 判断网络网络环境以及,阅读模式
     */
    public void getType() {
        model = PrefUtils.getInt("model", SettingsModelState.MODEL_TEXT_AND_IMAGE, mActivity);
        Log.i("model", model + "模式");
        networkType = NetworkStateUtils.network(mActivity);
        Log.i("model", networkType + "网络状态");
    }

    /**
     * 轮播广告
     */
    private void addListViewHeadView() {
        //轮播广告
        head = View.inflate(mActivity, R.layout.head_top_news, null);
        banner = (BGABanner) head.findViewById(R.id.banner_splash_pager);
        tvTopNewsTitle = (TextView) head.findViewById(R.id.tv_top_news_title);
        String topNewsHeadCache = PrefUtils.getString("TopNewsHead", "", mActivity);
        if (!topNewsHeadCache.isEmpty()) {
            analysisJsonDate(topNewsHeadCache);
            Log.i("topImageCache", "轮播的缓存数据");
        }
        lvContent.addHeaderView(head);
        getImagesForService();
//        headModel();
    }

    /**
     * 头条根据模式设置是否显示
     */
    private void headModel() {
        Log.i("headModel", " 当前模式:" + model);
        if (model == SettingsModelState.MODEL_TEXT) {
            lvContent.removeHeaderView(head);
            Log.i("headModel", "文本模式隐藏head");
        } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
            //智能模式
            if (networkType != ConnectivityManager.TYPE_WIFI) {
                //wifi状态
                lvContent.removeHeaderView(head);
                Log.i("headModel", "不是WIFI不显示head");
            } else {
                lvContent.removeHeaderView(head);
                lvContent.addHeaderView(head);
                head.setVisibility(View.VISIBLE);
                Log.i("headModel", "wifi下显示head");
            }
        } else if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
            lvContent.removeHeaderView(head);
            Log.i("headModel", "图文模式显示head");
        }
    }

    /**
     * 解析轮播广告数据
     *
     * @param date
     */

    public void analysisJsonDate(String date) {
        Log.i("imageData", date);
        Gson gson = new Gson();
        TopNewHeadBean dateBean = gson.fromJson(date, TopNewHeadBean.class);
        mTopNewsHeadList = (ArrayList<TopNewHeadBean.RowsBean>) dateBean.getRows();
        bitmapUtils = new BitmapUtils(mActivity);
        banner.setPageChangeDuration(1000);
        banner.setAutoPlayAble(true);
        tvTopNewsTitle.setText(mTopNewsHeadList.get(0).getTITLE());//默认显示第一张
        ArrayList<View> views = new ArrayList<>();
        for (int i = 0; i < mTopNewsHeadList.size(); i++) {
            TopNewHeadBean.RowsBean rowsBean = mTopNewsHeadList.get(i);
            views.add(getPageView(rowsBean.getPATHANDURL()));
        }
        banner.setData(views);
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                String title = mTopNewsHeadList.get(position).getTITLE();
                tvTopNewsTitle.setText(title);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        banner.setOnItemClickListener(new BGABanner.OnItemClickListener() {
            @Override
            public void onBannerItemClick(BGABanner banner, View view, Object model, int position) {
                if (position < myAdapter.getCount()) {
                    TopNewHeadBean.RowsBean item = mTopNewsHeadList.get(position);
                    Intent intent = new Intent(mActivity, NewsDetailedActivity.class);
                    intent.putExtra("title", item.getCHANNELNAME());
                    intent.putExtra("code", item.getID());
                    intent.putExtra("head", item.getTITLE());
                    intent.putExtra("cid", Constants.ID_TOP_NEW);
                    mActivity.startActivity(intent);
                }
            }
        });

    }


    private View getPageView(String src) {
        ImageView imageView = new ImageView(mActivity);
        bitmapUtils.display(imageView, src);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return imageView;


    }

    /**
     * 从服务器获取轮播广告的数据
     */
    public void getImagesForService() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpMethod.GET, Constants.URL_TOP_NEW_HEAD, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                analysisJsonDate(responseInfo.result);
                PrefUtils.putString("TopNewsHead", responseInfo.result, mActivity);
//                Log.i("")
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }

    class MyAdapter extends BaseAdapter {
        BitmapUtils bitmapUtils;

        MyAdapter() {
            bitmapUtils = new BitmapUtils(mActivity);
        }

        @Override
        public int getCount() {
            int count = mListFocusNews.size() + mListPolicy.size() + mListVideo.size();//加上标题栏
            return count + 3;//加上三个标题栏
        }

        @Override
        public DateBean.RowsBean getItem(int position) {

            if (position == 0 || position == 4 || position == 8) {//标题栏则啥都不返回
                return null;
            }
            if (position < mListFocusNews.size() + 1) {
                return mListFocusNews.get(position - 1);//减去标题栏
            } else if (position < mListVideo.size() + mListFocusNews.size() + 2) {
                return mListVideo.get(position - (mListFocusNews.size()) - 2);
            } else {
                return mListPolicy.get(position - (mListFocusNews.size() + mListVideo.size()) - 3);
            }

        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0 || position == 4 || position == 8) {//标题栏则啥都不返回
                return 0;//标题
            } else {
                return 1;//普通数据
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int type = getItemViewType(position);
            if (type == 1) {
                ViewHolder holder;
                if (convertView == null) {
                    convertView = View.inflate(mActivity, R.layout.item_date_content, null);
                    holder = new ViewHolder(convertView);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                DateBean.RowsBean date = getItem(position);
                //判断服务器是否返回图片，没有就影藏图片控件
                Log.i("imagePath", date.getPATHANDURL());
                if (!date.getPATHANDURL().isEmpty()) {
                    //图文模式
                    if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
                        holder.ivPhoto.setVisibility(View.VISIBLE);
                        bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                    } else if (model == SettingsModelState.MODEL_TEXT) {
                        //文本模式
                        holder.ivPhoto.setVisibility(View.GONE);
                    } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
                        //智能模式
                        if (networkType == ConnectivityManager.TYPE_WIFI) {
                            //wifi状态
                            holder.ivPhoto.setVisibility(View.VISIBLE);
                            bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                        } else {
                            holder.ivPhoto.setVisibility(View.GONE);
                        }
                    }

                } else {
                    holder.ivPhoto.setVisibility(View.GONE);
                }
                holder.tvTitle.setText(date.getTITLE());
                holder.tvTime.setText(date.getTIME());
                holder.tvType.setText(date.getCHANNELNAME());
                return convertView;
            } else {
                View view = View.inflate(mActivity, R.layout.item_top_title, null);
                TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
                switch (position) {
                    case 0:
                        tvTitle.setText("政务要闻");
                        break;
                    case 4:
                        tvTitle.setText("视频报道");
                        break;
                    case 8:
                        tvTitle.setText("政策解读");
                        break;
                }
                return view;

            }
        }


    }

    public class ViewHolder {
        @Bind(R.id.iv_news_photo)
        ImageView ivPhoto;
        @Bind(R.id.tv_news_title)
        TextView tvTitle;
        @Bind(R.id.tv_news_time)
        TextView tvTime;
        @Bind(R.id.tv_news_type)
        TextView tvType;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
